<template>
<div class="rolse-box">
  <!--面包屑-->
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!--角色列表-->
  <el-row>
    <el-card>
      <!--添加角色-->
      <el-row>
        <el-button  type="primary" @click="addRole">添加角色</el-button>
      </el-row>
      <!--角色列表表格-->
      <el-table
        :data="roleList"
        border
        style="width: 100%">
        <el-table-column
          type="expand">
          <template v-slot="scope">
            <el-row  class="bd-bottom"  v-for="(item1, index) in scope.row.children" :key="item1.id">
              <el-col :span="3">
                <el-tag  closable  @close="deleteRolesPrmission(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="21">
                <el-row  :span="4"   class="bd-bottom"  v-for="(item2, index) in item1.children" :key="item2.id">
                  <el-tag type="success" closable  @close="deleteRolesPrmission(scope.row,item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                  <el-col :span="20">
                      <el-tag type="warning" closable v-for="(item3, index) in item2.children" :key="item3.id"   @close="deleteRolesPrmission(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          label="#"
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="300">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述">
        </el-table-column>
        <el-table-column
          label="操作"
          width="400">>
          <template v-slot="scope">
            <!--编辑用户信息-->
            <el-button type="primary" icon="el-icon-edit" size="medium"
                       @click="editRoles(scope.row.id)"></el-button>
            <!--删除用户信息-->
            <el-button type="danger" icon="el-icon-delete" size="medium"
                       @click="deleteRoles(scope.row.id)"></el-button>
            <!--权限分配-->
            <el-tooltip content="权限分配" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-setting" size="medium" @click="ShowRolesRight(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--编辑角色信息-->
      <el-dialog
        title="编辑角色信息"
        :visible.sync="dialogRolesVisible"
        :close-on-click-modal="false"
        modal
        width="30%">
        <!--内容区-->
        <div>
          <el-form :model="rolesInfo" :rules="rolesInfoRules" ref="rolesInfo" label-width="100px"
                   class="demo-ruleForm">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="rolesInfo.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="rolesInfo.roleDesc"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelRolesEdit">取 消</el-button>
          <el-button type="primary" @click="updateRolesEdit">确 定</el-button>
        </span>
      </el-dialog>

      <!--添加角色信息-->
      <el-dialog
        title="添加角色信息"
        :visible.sync="dialogAddRolesVisible"
        :close-on-click-modal="false"
        modal
        width="30%">
        <!--内容区-->
        <div>
          <el-form :model="addRolesInfo" :rules="rolesInfoRules" ref="addRolesInfo" label-width="100px"
                   class="demo-ruleForm">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addRolesInfo.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addRolesInfo.roleDesc"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelRolesAdd">取 消</el-button>
          <el-button type="primary" @click="addRolesConfirm">确 定</el-button>
        </span>
      </el-dialog>

      <!--分配权限对话框-->
      <el-dialog
        title="分配权限"
        :visible.sync="dialogRolesRightVisible"
        :close-on-click-modal="false"
        width="50%"
        @close="handCloseRolesDialog"
      >
        <div class="rights-list-box">
          <el-tree :data="rightsData"
                   :props="treeProps"
                   show-checkbox
                   node-key="id"
                   :default-expand-all= true
                   :default-checked-keys="checkList"
                   ref="treeInfo"
                   @node-click="handleNodeClick">
          </el-tree>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogRolesRightVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmRolesRights()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </el-row>
</div>
</template>

<script>
export default {
  name: 'roles',
  data(){
    return {
      roleList: [],
      // 更新角色信息
      dialogRolesVisible: false,
      // 添加角色显示弹窗
      dialogAddRolesVisible: false,
      // 更新角色信息
      rolesInfo:{
        roleId: 0,
        roleName: '',
        roleDesc: ''
      },
      // 添加角色信息
      addRolesInfo:{
        roleName: '',
        roleDesc: ''
      },
      // 树形节点显示
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形节点默认勾选
      checkList: [],
      // 新增用户规则
      rolesInfoRules: {
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        roleDesc: [
          {required: true, message: '角色描述', trigger: 'blur'},
          {min: 3, max:30, message: '长度在 3 到 30 个字符', trigger: 'blur'}
        ],
      },
      // 是否显示分配权限对话框
      dialogRolesRightVisible: false,
      // 树形权限列表
      rightsData:[],
      roleId: ''
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    // 获取权限列表
    async getRoles(){
      const {data: res} = await this.$http.get('roles')
      if(res.meta.status !== 200) return this.$message.error('获取角色信息失败！')
      // this.$message.success( res.meta.msg)
      this.roleList = res.data
    },
    // 获取角色信息
    async editRoles(id) {
      const {data: res} = await this.$http.get(`roles/${id}`)
      if(res.meta.status !==200) return this.$message.error(res.meta.msg)
      this.rolesInfo = res.data
      this.dialogRolesVisible = true
      // this.$message.success(res.meta.msg)
    },
    // 更新角色信息
     updateRolesEdit(){
      this.$refs.rolesInfo.validate(async(valid)=>{
        if( !valid) return false
        const {data: res} = await this.$http.put(`roles/${this.rolesInfo.roleId}`, {roleName: this.rolesInfo.roleName, roleDesc: this.rolesInfo.roleDesc})
        if(res.meta.status !==200) return this.$message.error(res.meta.msg)
        this.getRoles()
        this.$message.success(res.meta.msg)
        this.dialogRolesVisible = false
      })
    },
    // 取消角色信息
    cancelRolesEdit(id){
      this.dialogRolesVisible = false
    },
    // 增加角色
    addRole() {
      this.dialogAddRolesVisible = true
    },
    // 取消增加角色操作
    cancelRolesAdd() {
      this.dialogAddRolesVisible = false
    },
    // 添加角色确定
    addRolesConfirm() {
      this.$refs.addRolesInfo.validate( async(valid)=>{
        if (!valid) return false
        const {data: res} = await this.$http.post(`roles`, this.addRolesInfo)
        if(res.meta.status !==201) return this.$message.error(res.meta.msg)
        this.getRoles()
        this.$message.success(res.meta.msg)
        this.dialogAddRolesVisible = false
        this.$refs.addRolesInfo.resetFields()
      })
    },
    // 删除角色
    async deleteRoles(id) {
      const confirmMessage = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((error) => {
        return error
      })
      if(confirmMessage !== 'confirm') return this.$message.info('已取消删除角色操作！')
      const {data: res} = await this.$http.delete(`roles/${id}`)
      if(res.meta.status !==200) return this.$message.error(res.meta.msg)
      this.getRoles()
      this.$message.success(res.meta.msg)
    },
    // 分配权限
    async ShowRolesRight(role) {
      // 存储将要分配权限的id值
      this.roleId = role.id
      this.dialogRolesRightVisible = true
      const {data: res} = await this.$http.get(`rights/tree`)
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsData = res.data
      this.getLeafKeys(role, this.checkList)
    },
    // 删除角色指定权限
    async deleteRolesPrmission(roles,rightId) {
      console.log('删除角色指定权限', roles,rightId)
      const confirmMessage = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).catch((error) => {
        return error
      })
      if(confirmMessage !== 'confirm') return this.$message.info('已取消删除操作！')
      const {data: res} = await this.$http.delete(`roles/${roles.id}/rights/${rightId}`)
      if(res.meta.status !==200) return this.$message.error(res.meta.msg)
      // 会引起表格的重新渲染
      // this.getRoles()
      roles.children = res.data
      this.$message.success(res.meta.msg)
    },
    handleNodeClick() {
      console.log('000000000')
    },
    // 递归检查子节点id放进数组checkList
    getLeafKeys(node, arr) {
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach((item)=>{
        this.getLeafKeys(item, arr)
      })
    },
    handCloseRolesDialog() {
      // 每次关闭对话框清空数组
      this.checkList = []
    },
    // 为角色分配权限
    async confirmRolesRights() {
      console.log('分配权限确认按钮点击事件', this.roleId)
      // ...展开数组 并合并成新数组
      const treeCheck =
        [
          ...this.$refs.treeInfo.getHalfCheckedKeys(), ...this.$refs.treeInfo.getCheckedKeys()
        ]
      // 使用逗号形成字符串
      const idsStr = treeCheck.join(',')
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids:idsStr})
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getRoles()
      this.dialogRolesRightVisible = false
      this.$message.success(res.meta.msg)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
